import {toast} from "../../utils/tool";

const app = getApp();
let eventChannel = null
Page({
    data: {
        list: [],
        allData: [],
        keyword: '',
    },
    onInput(ev) {
        const {value} = ev.detail
        this.setData({
            keyword: value
        })
    },
    deleteCart(ev) {
        eventChannel.emit('delHandler', ev)
        const {good} = ev.currentTarget.dataset
        const {id} = good
        const {list} = this.data
        const targetGood = list.find(item => item.id === id)
        const num = targetGood.num - 1
        if (num <= 0) {
            targetGood.num = 0
        } else {
            targetGood.num = num
        }
        this.setData({
            list: [...list]
        })
        const _index = this.data.allData.findIndex(item => item.id === id)
        this.data.allData[_index].num = targetGood.num
    },
    addCart(ev) {
        eventChannel.emit('addHandler', ev)
        const {good} = ev.currentTarget.dataset
        const {id} = good
        const {list} = this.data
        const targetGood = list.find(item => item.id === id)
        targetGood.num += 1
        this.setData({
            list: [...list]
        })
        const _index = this.data.allData.findIndex(item => item.id === id)
        this.data.allData[_index].num = targetGood.num
    },

    searchHandler() {
        const {keyword} = this.data
        if (!keyword.length) return toast({title: '请输入关键字'})
        const {allData} = this.data
        const list = allData.filter(item => {
            return item.name === keyword || item.name.includes(keyword)
        })
        this.setData({list})
    },

    getCartData(ev) {
        const allData = app.getShopList()
        if (!!ev && ev.length) {
            ev.forEach(item => {
                const index = allData.findIndex(good => good.id === item.id)
                if (index === -1) return
                const {index: _index} = allData[index]
                allData[index] = {...item, index: _index}
            })
        }
        this.data.allData = allData
    },
    calcNum(ev) {
        console.log(ev)
    },
    onLoad: function (options) {
        if (!eventChannel) {
            eventChannel = this.getOpenerEventChannel()
            eventChannel.on('getCartData', this.getCartData)
            eventChannel.on('calcNum', this.calcNum)
        }
    },
    onUnload() {
        if (!eventChannel) return
        eventChannel.off('getCartData', this.getCartData)
        eventChannel.off('calcNum', this.calcNum)
        eventChannel = null
    },

});